package com.wangwenjun.concurrency.chapter14.reentrantlock;

import java.util.concurrent.locks.ReentrantLock;

public class UseReentrantLock2 {

    public static void main(String[] args) throws InterruptedException {

        Chopsticks c1 = new Chopsticks();
        Chopsticks c2 = new Chopsticks();
        Chopsticks c3 = new Chopsticks();
        Chopsticks c4 = new Chopsticks();
        Chopsticks c5 = new Chopsticks();


        new Person("A", c1, c2).start();
        new Person("B", c2, c3).start();
        new Person("C", c3, c4).start();
        new Person("D", c4, c5).start();
        new Person("E", c5, c1).start();

    }







}

class Person extends Thread{

    private String name;

    private Chopsticks left;

    private Chopsticks right;

    public Person(String name, Chopsticks left, Chopsticks right){
        this.name = name;
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        while (true){
           if(left.tryLock()){
                try {
                    if(right.tryLock()){
                        try {
                            try {
                                eat();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }finally {
                            right.unlock();
                        }
                    }
                }finally {
                    left.unlock();
                }
           }
        }
    }

    private void eat() throws InterruptedException {
        System.out.println(name+" is eating");
        Thread.sleep(100);
    }

}

class Chopsticks extends ReentrantLock{



}